/*-+-*****************************************************************************
 Copyright (C) 2009-2012 Oceanside Software Corporation (R)
 Dallas, Texas

 Author       : Jason T. Brower
 Purpose      : This file is part of a point-of-sale software package
                originally written for Table-Service Restaurants.
              
 Date         : July 8th of 2012
              
 History      : The application that this software file belongs to was 
                written over a 3-Year period.  The first version was written
                in C# .Net 3.5 using Windows Forms.  Being new to .Net at
                the time, I soon learned of Windows Presentation Foundation,
                liked the graphics capabilities and databinding so I
                migrated to WPF.  When the .Net 4.0 framework was released
                the application was migrated from 3.5 to 4.0. Now today,
                .Net 4.5 RC is out and I was already in process of migrating
                before I made this public.
                
Excuse Me     : Please excuse the coding style, it is not representative of
                my typical work.  During the three years I was under a very
                tight budget, constantly running out of funding and was 
                working 18 hour days hyped up on 5-Hour Energy.  The 
                design is not textbook.  It is monolythic because of
                previous issues I will not get into.  There are few comments
                in the code and the ones that are there may be incorrect.
                
What it is not: This is not the exact version that I took through PA-DSS 2.0
                nor is it the exact version running at my customer sites.
                I removed some details for security purposes including some
                encryption algorithms.  The reporting was removed because
                I was including a third party library that cannot be 
                published with this Open Source.
                
What it is    : This application has been running at high volume restaraunts
                for over a year.  It never freezes, crashes or does anything
                unexpected.  So long as it is built, installed and configured
                correctly, it is a strong system that we can all enhance.

Contact       : Please note that I can no longer work for free.  However, you
                can reach me at information@oceansidesw.com.                                                      

*********************************************************************************/
using System.Collections.Generic;
using System.Data.Objects.DataClasses;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System;
#if _LOCALDB
  using Oceanside.LocalDB;
#else
using Oceanside.RemoteDB;
#endif

namespace Oceanside
{
    /// <summary>
    /// Interaction logic for PageLogin.xaml
    /// </summary>
    public partial class PageLayoutImp : PageImpBaseClass
    {
        static Button_95_50 _selectedButton = null;
        public static Button_95_50 SelectedButton
        {
            get { return PageLayoutImp._selectedButton; }
            set { PageLayoutImp._selectedButton = value; }
        }

        static LAYOUTOBJ _layoutObj = null;
        public static LAYOUTOBJ LayoutObj
        {
            get { return PageLayoutImp._layoutObj; }
            set { PageLayoutImp._layoutObj = value; }
        }

        WrapPanel w1;
        WrapPanel w2;
        WrapPanel w3;

        List<WrapPanel> wplist = null;
        DbLinkedBoundListView listviewChosenProd;
        ListView listviewAvailableProds;
        TextBox tbtag;
        DbLinkedTextBox tbButtonName;
        Button bRemoveSelected;
        ComboBox cbStyles;
        ComboBox cbGroups;

        /// <summary>
        /// Constructor
        /// </summary>
        public PageLayoutImp(UIElementCollection elements, WrapPanel w1, WrapPanel w2, WrapPanel w3,
            ComboBox cbStyles, Button bAddSelected, Button bRemoveSelected,
            DbLinkedBoundListView listviewChosenProd, ListView listviewAvailableProds, TextBox tbtag, DbLinkedTextBox tbButtonName, ComboBox cbGroups, GroupBox mainGroup)
            : base()
        {
            this.ButtonNumber = "";
            this.ButtonLabelText = "Map Order Buttons";
            this.listviewAvailableProds = listviewAvailableProds;
            this.listviewChosenProd = listviewChosenProd;

            RegisterSaveMeGroupBoxes(null, mainGroup);
            this.w1 = w1;
            this.w2 = w2;
            this.w3 = w3;
            this.tbButtonName = tbButtonName;
            this.tbtag = tbtag;
            this.bRemoveSelected = bRemoveSelected;
            this.cbStyles = cbStyles;
            this.cbGroups = cbGroups;
            cbStyles.SelectionChanged += new SelectionChangedEventHandler(cbStyles_SelectionChanged);
            cbGroups.SelectionChanged += new SelectionChangedEventHandler(cbGroups_SelectionChanged);
            cbStyles.Items.Add("Brown");
            cbStyles.Items.Add("Light Blue");
            cbStyles.Items.Add("Dark Blue");
            cbStyles.Items.Add("Green");

            wplist = new List<WrapPanel>(3);
            wplist.Add(w1);
            wplist.Add(w2);
            wplist.Add(w3);
            SetDesignerEventHandlers();
            mNewEntityIsDisabled = true;
            mDeleteEntityIsDisabled = true;
            mCancelIsDisabled = true;
            mEditIsDisabled = true;
            mSaveIsDisabled = true;

            bAddSelected.Click += new RoutedEventHandler(buttonAddSelectedProd_Click);
            bRemoveSelected.Click += new RoutedEventHandler(buttonRemSelectedProd_Click);

            ///Register the controls and lock the form.
            RegisterUiElementsList(elements);

            ///Add all text boxes to the list.
            mEntityAddDeleteLoggingEnabled = false;

            tbButtonName.TextChanged += new TextChangedEventHandler(tbButtonName_TextChanged);

        }

        void cbGroups_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            UpdateListViews();
        }

        private static string GetStyleResourceName(string name)
        {
            string styleName = "QSNotSetStyle";
            if (name != null)
            {
                if (name.Equals("Brown"))
                {
                    styleName = "PlaceOrderFuncButtonFirst";
                }
                else if (name.Equals("Light Blue"))
                {
                    styleName = "DoneCancelStyle";
                }
                else if (name.Equals("Dark Blue"))
                {
                    styleName = "DarkBlueStyle";
                }
                else if (name.Equals("Green"))
                {
                    styleName = "AddGratuityButtonStyle";
                }
            }
            return styleName;
        }

        private static string GetResourceStyleName(string name)
        {
            string resourceName = "QSNotSetStyle";
            if (name != null)
            {
                if (name.Equals("PlaceOrderFuncButtonFirst"))
                {
                    resourceName = "Brown";
                }
                else if (name.Equals("DoneCancelStyle"))
                {
                    resourceName = "Light Blue";
                }
                else if (name.Equals("DarkBlueStyle"))
                {
                    resourceName = "Dark Blue";
                }
                else if (name.Equals("AddGratuityButtonStyle"))
                {
                    resourceName = "Green";
                }
            }
            return resourceName;
        }

        void cbStyles_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (_layoutObj != null & e.AddedItems != null & e.AddedItems.Count != 0)
            {
                _layoutObj.Style = GetStyleResourceName(e.AddedItems[0] as string);
                if (_layoutObj.Id != 0)
                {
                    Context.SaveChanges();
                }
            }
        }

        void tbButtonName_TextChanged(object sender, TextChangedEventArgs e)
        {
            DbLinkedTextBox tb = sender as DbLinkedTextBox;
            if (_selectedButton != null && _layoutObj != null)
            {
                if (_selectedButton.Tag.Equals(_layoutObj.Tag))
                {
                    _selectedButton.ButtonLabelText = tb.Text;
                    _layoutObj.ButtonText = tb.Text;
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonAddSelectedProd_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_layoutObj != null)
                {
                    PRODUCT_GROUP pg = cbGroups.SelectedItem as PRODUCT_GROUP;
                    PRODUCT p = listviewAvailableProds.SelectedItem as PRODUCT;
                    if (p != null && pg != null)
                    {
                        _selectedButton.ButtonLabelText = p.Name;
                        _layoutObj.ButtonText = p.Name;
                        _layoutObj.ProductId = p.Id;
                        _layoutObj.PagedId = PAGELAYOUT.CONST_PAGE_TYPE_ORDERSCREEN;
                        _layoutObj.Tag = _selectedButton.Tag as string;
                        _layoutObj.CategoryId = pg.Id;
                        if (cbStyles.SelectedValue == null)
                        {
                            _layoutObj.Style = "PlaceOrderFuncButtonFirst";
                        }
                        else
                        {
                            _layoutObj.Style = GetStyleResourceName(cbStyles.SelectedValue as string);
                        }
                        if (_layoutObj.Id == 0)
                        {
                            Context.LAYOUTOBJS.AddObject(_layoutObj);
                        }
                        Context.SaveChanges();
                    }
                    UpdateListViews();
                }
            }
            catch { }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonRemSelectedProd_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_layoutObj != null)
                {
                    if (_layoutObj.Id != 0)
                    {
                        Context.LAYOUTOBJS.DeleteObject(_layoutObj);
                    }
                    Context.SaveChanges();
                }
                SetButtonStyle(_selectedButton);
                _selectedButton = null;
                _layoutObj = null;
                tbButtonName.IsEnabled = false;
                cbStyles.SelectedValue = null;
                bRemoveSelected.Visibility = Visibility.Hidden;
                UpdateListViews();
            }
            catch { }
        }
        /// <summary>
        /// 
        /// </summary>
        private void UpdateListViews()
        {
            PRODUCT_GROUP pg = cbGroups.SelectedItem as PRODUCT_GROUP;
            if (_layoutObj != null)
            {
                if (pg != null)
                {
                    List<PRODUCT> prods = pg.PRODUCTS.
                                     Where(P => P.IsDeleted == false).OrderBy(P => P.Name).ToList();

                    PRODUCT used = Context.PRODUCTS.Where(p => p.Id == _layoutObj.ProductId).FirstOrDefault();
                    List<PRODUCT> usedList = new List<PRODUCT>();
                    if (used != null)
                    {
                        usedList.Add(used);
                    }
                    listviewAvailableProds.ItemsSource = prods;
                    listviewChosenProd.ItemsSource = usedList;

                    if (_selectedButton != null)
                    {
                        if (_layoutObj.ButtonText == null && used != null)
                        {
                            tbButtonName.Text = used.Name;
                        }
                        else
                        {
                            tbButtonName.Text = _layoutObj.ButtonText;
                        }
                        tbtag.Text = _selectedButton.Tag as string;
                    }
                }
                else
                {
                    listviewAvailableProds.ItemsSource = null;
                    listviewChosenProd.ItemsSource = null;
                    tbtag.Text = null;
                    tbButtonName.Text = null;
                }
            }
            else
            {
                if (pg != null)
                {
                    listviewAvailableProds.ItemsSource = pg.PRODUCTS.
                                     Where(P => P.IsDeleted == false).OrderBy(P => P.Name).ToList();
                }
                else
                {
                    listviewAvailableProds.ItemsSource = null;
                }
                listviewChosenProd.ItemsSource = null;
                tbtag.Text = null;
                tbButtonName.Text = null;
            }
        }

        private void SetDesignerEventHandlers()
        {
            foreach (WrapPanel wp in wplist)
            {
                foreach (UIElement el in wp.Children)
                {
                    if (el is Button_95_50)
                    {
                        Button_95_50 b = (el as Button_95_50);
                        b.MouseDown += new System.Windows.Input.MouseButtonEventHandler(b_MouseDown);
                    }
                }
            }
        }

        public override void Navigating()
        {
            base.Navigating();

            if (Constants.IsQuickServiceMode)
            {
                Init.LoadDynamicOrderButtons();
            }
        }
        void b_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            tbButtonName.IsEnabled = true;
            _layoutObj = null;
            if (_selectedButton != null)
            {
                SetButtonStyle(_selectedButton);
            }
            _selectedButton = sender as Button_95_50;
            SetButtonStyle(_selectedButton, true);

            ///See if a layout object exists for the selected button.
            string tag = _selectedButton.Tag as string;
            LAYOUTOBJ lo = Context.LAYOUTOBJS.Where(o => o.PagedId == PAGELAYOUT.CONST_PAGE_TYPE_ORDERSCREEN
                && o.Tag != null && o.Tag.Equals(tag)).FirstOrDefault();
            if (lo == null)
            {
                lo = new LAYOUTOBJ();
                lo.Tag = _selectedButton.Tag as string;
                cbStyles.SelectedValue = null;
                bRemoveSelected.Visibility = Visibility.Hidden;
            }
            else
            {
                bRemoveSelected.Visibility = Visibility.Visible;
                cbStyles.SelectedValue = GetResourceStyleName(lo.Style);
            }
            _layoutObj = lo;
            UpdateListViews();
        }

        private void SetButtonStyle(Button_95_50 b, bool isSelected = false)
        {
            string tag = b.Tag as string;
            LAYOUTOBJ lo = null;
            if (!String.IsNullOrEmpty(tag))
            {
                lo =
                    Context.LAYOUTOBJS.
                    Where(o => o.PagedId == PAGELAYOUT.CONST_PAGE_TYPE_ORDERSCREEN && o.Tag != null && o.Tag.Equals(tag)).FirstOrDefault();
            }

            if (lo != null && !string.IsNullOrEmpty(lo.Style))
            {
                if (isSelected)
                {
                    b.SetResourceReference(Button_95_50.StyleProperty, "QSDesignerSelected");
                }
                else
                {
                    b.SetResourceReference(Button_95_50.StyleProperty, lo.Style);
                }
                PRODUCT p = Context.PRODUCTS.Where(pr => pr.Id == lo.ProductId).FirstOrDefault();

                if (string.IsNullOrEmpty(lo.ButtonText))
                {
                    tbButtonName.Text = null;
                    b.ButtonLabelText = "Not Used";
                }
                else
                {
                    tbButtonName.Text = lo.ButtonText;
                    b.ButtonLabelText = lo.ButtonText;
                }
            }
            else
            {
                if (isSelected)
                {
                    b.SetResourceReference(Button_95_50.StyleProperty, "QSDesignerSelected");
                }
                else
                {
                    b.SetResourceReference(Button_95_50.StyleProperty, "QSNotSetStyle");
                }
                tbButtonName.Text = null;
                b.ButtonLabelText = "Not Used";
            }
        }
        public void LoadButtonDetails()
        {
            try
            {
                _selectedButton = null;
                _layoutObj = null;
                tbButtonName.Text = null;
                tbtag.Text = null;
                bRemoveSelected.Visibility = Visibility.Hidden;
                cbStyles.SelectedValue = null;

                    var q = from PG in Context.PRODUCT_GROUPS where PG.IsDeleted == false select PG;
                    if (q.Any())
                    {
                        cbGroups.ItemsSource = q.ToList();
                    }
                UpdateListViews();
                foreach (WrapPanel wp in wplist)
                {
                    foreach (UIElement el in wp.Children)
                    {
                        if (el is Button_95_50)
                        {
                            Button_95_50 b = (el as Button_95_50);
                            SetButtonStyle(b);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
            }
        }
    }
}
